<?php
namespace app\common\Util;
use \DOMDocument;

class DomUtil extends DOMDocument{
    //$node是要解析的节点,$data是保存结果的数组，解析后的数据会作为$data中的一项
    //XML中同级的标签可以同名，PHP数组中不能同名，所以要将同名的节点都放在一个List中
    //文字放在text属性中
    //属性放在attributes属性中
    //子节点放在children属性中
    //如果只有一个属性，则只返回这个属性
    public function parseXMLNode($node){
        $childNodes=$node->childNodes;
        $attrNodes=$node->attributes;
        $textNodes=$childNodes[0];
    
        $flag=0;
        $data=[];
    
        $text="";
        if($textNodes){
            $text=$textNodes->textContent;
            if(!preg_match("/^[\s]*$/",$text)){
                $flag+=1;
                $data["text"]=$text;
            }
        }
    
        $attributes=[];
        if($attrNodes && $attrNodes->length>0){
            foreach($attrNodes as $attrNode){
                $attributes[$attrNode->localName]=$attrNode->textContent;
            }
            $flag+=10;
            $data["attributes"]=$attributes;
        }
    
        $children=[];
        if($childNodes && $childNodes->length>1){
            foreach($childNodes as $key => $childNode){
                if($key===0) continue;
                $localName=$childNode->localName;
                $listName=$localName."List";
                $child=$this->parseXMLNode($childNode);
                if($child===null) continue;
                if(isset($children[$localName])){
                    $children[$listName]=[$children[$localName],$child];
                    unset($children[$localName]);
                }
                elseif(isset($children[$listName])){
                    $children[$listName][]=$child;
                }
                else{
                    $children[$localName]=$child;
                }
            }
            $flag+=100;
            $data["children"]=$children;
        }
        
        if($flag===0){
            return null;
        }
        elseif($flag===1){
            $data=$text;
        }
        elseif($flag===10){
            $data=$attributes;
        }
        elseif($flag===100){
            $data=$children;
        }
        return $data;
    }
}